package com.lalameow.loreattr.attribute.attribute.valueattribute;

import com.lalameow.loreattr.attribute.attribute.AbstractValueAttribute;
import com.lalameow.loreattr.attribute.entity.EntityAttribute;
import com.lalameow.loreattr.attribute.util.LoreUtils;
import org.bukkit.attribute.*;
import org.bukkit.attribute.Attribute;
import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.ItemStack;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author: SettingDust
 * Date: 2017/6/21.
 */
public class AttributeHealth extends AbstractValueAttribute {
    private final Pattern add = Pattern.compile("[+](\\d+)[ ](" + entityAttribute.getKeyword().toLowerCase() + ")");
    private final Pattern neg = Pattern.compile("[-](\\d+)[ ](" + entityAttribute.getKeyword().toLowerCase() + ")");

    public AttributeHealth() {
        super(EntityAttribute.getAttribute("health"));
    }

    public double getAttribute(LivingEntity entity) {
        if (!entity.isValid()) {
            return 0;
        }
        return getValue(LoreUtils.getLore(entity, false, true));
    }

    public double getAttribute(ItemStack itemStack) {
        return getValue(LoreUtils.getLore(itemStack));
    }

    public double getValue(List<String> lore) {
        Integer hpToAdd = 0;
        for (String s : lore) {
            Matcher matcher = add.matcher(s.toLowerCase());
            Matcher negmatcher = neg.matcher(s.toLowerCase());
            if (matcher.find())
                hpToAdd += Integer.valueOf(matcher.group(1));
            if (negmatcher.find())
                hpToAdd -= Integer.valueOf(matcher.group(1));
        }
        return hpToAdd;
    }

    public void applyHp(LivingEntity entity) {
        AttributeInstance attribute = entity.getAttribute(Attribute.GENERIC_MAX_HEALTH);
        AttributeModifier attributeModifier = new AttributeModifier("loreattr_event", getAttribute(entity), AttributeModifier.Operation.ADD_NUMBER);
        for (AttributeModifier modifier : attribute.getModifiers()) {
            if (modifier.getName().equals("loreattr_event")) {
                attribute.removeModifier(modifier);
            }
        }
        attribute.addModifier(attributeModifier);
    }
}
